// import {
//     GPS
// } from './GPS2AMAP'
let callback = null // promise 的 resolve会赋值给这个函数
// import AMap from 'react-amap'
// gps 定位成功回调
const onSuccess = (position) => {
    const {
        latitude: lat,
        longitude: lng
    } = position.coords
    // const exchange = GPS.gcj_encrypt(Number.parseFloat(lat), Number.parseFloat(lng)) // 对精度要求不高可以省略这步，把上面获取到的经纬度直接传给saveLocation
    // console.log('gps定位', `${exchange.lat}-${exchange.lng}`)
    // alert('gps定位', `${exchange.lat}-${exchange.lng}`)这个地方获取GPS校准lng有问题
    saveLocation(Number.parseFloat(lat), Number.parseFloat(lng))
}
// gps 定位失败回调
const onError = () => {
    initAMAP()
    console.error('gps失败')
    // alert(1111)
}
// 初始化高德，加载高德js
const initAMAP = () => {
    const key = '6c11990ede40ff54f4401b963120730f', // 从高德买来的key
        MP = new Promise(function (resolve, reject) {
            window.init = function () {
                //eslint-disable-next-line 
                resolve(AMap)
            };
            let script = document.createElement("script");
            script.type = "text/javascript";
            script.src = "//webapi.amap.com/maps?v=1.4.6&key=" + key + "&callback=init";
            script.onerror = reject;
            document.head.appendChild(script);
        })
    MP.then(function (AMap) {
        startAMAPLocation(AMap)
    }).catch(err => {
        console.error(JSON.stringify(err));
    })
}

// 开始高德定位
const startAMAPLocation = (AMap) => {
    AMap.plugin('AMap.Geolocation', function () {
        var geolocation = new AMap.Geolocation({
            enableHighAccuracy: true, //是否使用高精度定位，默认:true
            timeout: 8000, //超过10秒后停止定位，默认：5s
            buttonPosition: 'RB', //定位按钮的停靠位置
            buttonOffset: new AMap.Pixel(10, 20), //定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
            zoomToAccuracy: true, //定位成功后是否自动调整地图视野到定位点
        });
        // map.addControl(geolocation);
        geolocation.getCurrentPosition(function (status, result) {
            if (status == 'complete') {
                console.log('高德: ', `${result.position.lat},${result.position.lng}`)

                saveLocation(result.position.lat, result.position.lng)
            } else {
                console.error('高德失败')
                saveLocation(0, 0)
            }
        });
    });
}
// 处理获取到的经纬度
const saveLocation = (lat = 0, lng = 0) => {
    lat && (lat = parseFloat(lat).toFixed(6))
    lng && (lng = parseFloat(lng).toFixed(6))
    typeof callback === 'function' && callback({ lat, lng })
}

// promise, resolve的第一个参数就是经纬度，
const startLocation = new Promise((resolve, reject) => {
    callback = resolve
    const options = {
        enableHighAccuracy: true,
        maximumAge: 1000,
        timeout: 5000
    }
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(onSuccess, onError, options)
    } else {
        saveLocation(0, 0)
        console.error('您的浏览器不支持地理位置定位')
    }
})
// var GPS = {
//     PI: 3.14159265358979324,
//     x_pi: 3.14159265358979324 * 3000.0 / 180.0,
//     delta: function (lat, lon) {
//         // Krasovsky 1940
//         //
//         // a = 6378245.0, 1/f = 298.3
//         // b = a * (1 - f)
//         // ee = (a^2 - b^2) / a^2;
//         var a = 6378245.0; //  a: 卫星椭球坐标投影到平面地图坐标系的投影因子。
//         var ee = 0.00669342162296594323; //  ee: 椭球的偏心率。
//         var dLat = this.transformLat(lon - 105.0, lat - 35.0);
//         var dLon = this.transformLon(lon - 105.0, lat - 35.0);
//         var radLat = lat / 180.0 * this.PI;
//         var magic = Math.sin(radLat);
//         magic = 1 - ee * magic * magic;
//         var sqrtMagic = Math.sqrt(magic);
//         dLat = (dLat * 180.0) / ((a * (1 - ee)) / (magic * sqrtMagic) * this.PI);
//         dLon = (dLon * 180.0) / (a / sqrtMagic * Math.cos(radLat) * this.PI);
//         return { 'lat': dLat, 'lon': dLon };
//     },

//     //GPS---高德
//     gcj_encrypt: function (wgsLat, wgsLon) {
//         alert('111111掉落')
//         if (this.outOfChina(wgsLat, wgsLon))
//             return { 'lat': wgsLat, 'lon': wgsLon };

//         var d = this.delta(wgsLat, wgsLon);
//         return { 'lat': wgsLat + d.lat, 'lon': wgsLon + d.lon };
//     },
//     outOfChina: function (lat, lon) {
//         if (lon < 72.004 || lon > 137.8347)
//             return true;
//         if (lat < 0.8293 || lat > 55.8271)
//             return true;
//         return false;
//     },
//     transformLat: function (x, y) {
//         var ret = -100.0 + 2.0 * x + 3.0 * y + 0.2 * y * y + 0.1 * x * y + 0.2 * Math.sqrt(Math.abs(x));
//         ret += (20.0 * Math.sin(6.0 * x * this.PI) + 20.0 * Math.sin(2.0 * x * this.PI)) * 2.0 / 3.0;
//         ret += (20.0 * Math.sin(y * this.PI) + 40.0 * Math.sin(y / 3.0 * this.PI)) * 2.0 / 3.0;
//         ret += (160.0 * Math.sin(y / 12.0 * this.PI) + 320 * Math.sin(y * this.PI / 30.0)) * 2.0 / 3.0;
//         return ret;
//     },
//     transformLon: function (x, y) {
//         var ret = 300.0 + x + 2.0 * y + 0.1 * x * x + 0.1 * x * y + 0.1 * Math.sqrt(Math.abs(x));
//         ret += (20.0 * Math.sin(6.0 * x * this.PI) + 20.0 * Math.sin(2.0 * x * this.PI)) * 2.0 / 3.0;
//         ret += (20.0 * Math.sin(x * this.PI) + 40.0 * Math.sin(x / 3.0 * this.PI)) * 2.0 / 3.0;
//         ret += (150.0 * Math.sin(x / 12.0 * this.PI) + 300.0 * Math.sin(x / 30.0 * this.PI)) * 2.0 / 3.0;
//         return ret;
//     }
// };
export default startLocation